<template>
  <div>
    <el-card>
      <el-col :span="24">
        <van-nav-bar
          title="修改昵称"
          left-text="返回"
          left-arrow
          @click-left="onClickLeft"
        />
      </el-col>
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="昵称">
          <el-input v-model="form.name"/>
        </el-form-item>
        <el-form-item>
          <van-button type="primary" @click="saveNickname">保存</van-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import axios from "axios";
import {Toast} from "vant";

export default {
  data() {
    return {
      user: {},
      uid: "",
      form: {
        name: "",
      }
    };
  },
  methods: {
    findById() {
      axios.post("/user/user/findById?id=" + this.uid).then(res => {
        this.user = res.data.data;
      })
    },
    onClickLeft() {
      Toast('返回');
      //返回上一个页面
      this.$router.push('/PersonalProfile');
    },
    // 重写后的saveNickname方法
    saveNickname() {
      // 先进行表单验证
      this.$refs.form.validate((valid) => {// 表单验证回调函数
        if (valid) {
          const newNickname = this.form.name.trim(); // 去除前后空格，避免无效的空格昵称
          if (newNickname === "") {
            // 如果昵称经过处理后为空，提示用户
            this.$message.error("昵称不能为空，请输入有效昵称");
            return;
          }
          axios.post(`/user/user/updateById?name=${this.form.name}&id=${this.uid}`).then(res => {
            // 提示保存成功信息
            this.$message.success("昵称保存成功");
            // 跳转到PersonalProfile页面（这里假设路由配置正确）
            this.$router.push({path: '/PersonalProfile'});
          })
        } else {
          console.log('表单验证失败');
          this.$message.error("表单验证不通过，请检查输入内容");
          return false;
        }
      });
    }
  },
  mounted() {
    const user = localStorage.getItem('user');
    if (user) {
      this.user = JSON.parse(user);
      this.uid = this.user.id;
      console.log("user=", this.user);
      this.findById();
    }
  }
};
</script>

<style scoped>
.el-card {
  margin-top: 20px;
}
</style>
